<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="所属类名" prop="cppClass">
        <el-input
          v-model="queryParams.cppClass"
          placeholder="请输入所属类名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <!-- <el-form-item label="API ID" prop="apiId">
        <el-input
          v-model="queryParams.apiId"
          placeholder="请输入API ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="作者" prop="updater">
        <el-select
          v-model="queryParams.updater"
          placeholder="请选择作者"
          clearable
          class="!w-240px"
          @change="handleAuthorChange"
        >
          <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['plus:docplus:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['plus:docplus:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" @sort-change="handleSortChange">
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="内容" align="center" prop="content" />
      <el-table-column label="示例代码" align="center" prop="democode">
        <template #default="scope">
          <el-tooltip placement="top-start">
            <template #content>
              <pre style="white-space:pre-wrap;max-width:600px">{{ scope.row.democode }}</pre>
            </template>
            <span class="truncate max-w-200px">{{ scope.row.democode }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="所属URL" align="center" prop="url">
        <template #default="scope">
          <el-link v-if="scope.row.url" :href="scope.row.url" target="_blank" type="primary">
            {{ scope.row.url }}
          </el-link>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="所属类名" align="center" prop="cppClass" />
      <!-- <el-table-column label="API ID" align="center" prop="apiId" min-width="120px" /> -->
      <el-table-column label="作者" align="center" prop="updaterName" min-width="100px" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
        sortable="custom"
        :sort-orders="['descending', 'ascending', null]"
      />
      <el-table-column label="操作" align="center" min-width="160px">
        <template #default="scope">
          <el-button link type="primary" @click="openSubmissionDialog(scope.row.id)">
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['plus:docplus:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['plus:docplus:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <DocplusForm ref="formRef" @success="getList" />

  <!-- 代码提交详情弹窗 -->
  <el-dialog v-model="submissionDialogVisible" title="运行详情" width="60%">
    <el-table v-loading="submissionLoading" :data="submissionList" stripe :show-overflow-tooltip="true">
      <el-table-column label="源码" prop="sourceCode">
        <template #default="scope">
          <el-tooltip :content="decodeSource(scope.row.sourceCode)" placement="top">
            <span>{{ decodeSource(scope.row.sourceCode) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="运行耗时(s)" prop="time" width="120" />
      <el-table-column label="内存使用量(KB)" prop="memory" width="160" />
      <el-table-column label="输出文件列表" prop="outfiles" />
    </el-table>
    <template #footer>
      <Pagination
        :total="submissionTotal"
        v-model:page="submissionQuery.pageNo"
        v-model:limit="submissionQuery.pageSize"
        @pagination="getSubmissionList"
      />
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DocplusApi, DocplusVO } from '@/api/plus/docplus'
import { SubmissionApi, SubmissionVO } from '@/api/plus/submission'
import DocplusForm from './DocplusForm.vue'
import { getSimpleUserList } from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import { useRoute } from 'vue-router'

/** 文档附加 列表 */
defineOptions({ name: 'Docplus' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<DocplusVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const userList = ref<UserVO[]>([]) // 用户列表
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id: '' as string | undefined,
  content: undefined,
  cppClass: undefined,
  apiId: undefined,
  createTime: [],
  updater: undefined,
  sortField: undefined as string | undefined,
  sortOrder: undefined as 'asc' | 'desc' | undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// ========== 提交详情相关 ==========
const submissionDialogVisible = ref(false)
const submissionLoading = ref(false)
const submissionList = ref<SubmissionVO[]>([])
const submissionTotal = ref(0)
const submissionQuery = reactive({
  pageNo: 1,
  pageSize: 10,
  plusid: ''
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DocplusApi.getDocplusPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: string) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DocplusApi.deleteDocplus(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DocplusApi.exportDocplus(queryParams)
    download.excel(data, '文档附加.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  const route = useRoute()
  if (route.query.plusid) {
    queryParams.id = route.query.plusid as string
  }
  getList()
  getUserList()
})

/** 获取用户列表 */
const getUserList = async () => {
  try {
    userList.value = await getSimpleUserList()
  } catch (e) {
    console.error('获取用户列表失败', e)
  }
}

/** 作者变更时自动执行搜索 */
const handleAuthorChange = () => {
  handleQuery()
}

/** 排序变化事件处理 */
const handleSortChange = (column) => {
  if (column.prop && column.order) {
    queryParams.sortField = column.prop
    queryParams.sortOrder = column.order === 'ascending' ? 'asc' : 'desc'
  } else {
    queryParams.sortField = undefined
    queryParams.sortOrder = undefined
  }
  getList()
}

const getSubmissionList = async () => {
  if (!submissionQuery.plusid) return
  submissionLoading.value = true
  try {
    const data = await SubmissionApi.getSubmissionPage(submissionQuery)
    submissionList.value = data.list
    submissionTotal.value = data.total
  } finally {
    submissionLoading.value = false
  }
}

const openSubmissionDialog = (plusId: string) => {
  submissionQuery.plusid = plusId
  submissionQuery.pageNo = 1
  getSubmissionList()
  submissionDialogVisible.value = true
}

const formatCode = (code: string) => {
  if (!code) return ''
  // 转义 HTML 并替换换行符为 <br/>
  return code
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\n/g, '<br/>')
}

const decodeSource = (sourceCode: string) => {
  if (!sourceCode) return ''
  try {
    return decodeURIComponent(escape(atob(sourceCode)))
  } catch (e) {
    return sourceCode
  }
}
</script>